import 'dart:convert';

import 'package:example_example/bean/BossBean.dart';
import 'package:example_example/global/Global.dart';
import 'package:example_example/global/GlobalUrl.dart';
import 'package:example_example/pages/person/Login.dart';
import 'package:example_example/util/HttpUtil.dart';
import 'package:example_example/util/ToastUtils.dart';
import 'package:package_info/package_info.dart';

import '../../YColors.dart';
import '../../services/ScreenAdapter.dart';
import '../../services/TLSizeFit.dart';
import '../../util/LogUtil.dart';
import 'package:flutter/material.dart';
import '../../util/Storage.dart';

class PersonCenter extends StatefulWidget {
  PersonCenter({Key key}) : super(key: key);

  _PersonCenterPage createState() => _PersonCenterPage();
}

class _PersonCenterPage extends State<PersonCenter> {
  var name = "";
  var id = "";

  var expires_in; // 工号

  var phone = "";

  var version ='';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    LogUtil.v("initState: 个人...initState");
    getStorageData();
    getVersionNumber();
  }

  getStorageData() async {
    var strStor = await Storage.getString(Global.LOGINDATA);
    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
    LogUtil.v("有缓存strStor:$strStor");

    var logBean = json.decode(strStor); // Json 字符串转化成 Map 类型

    name = logBean["name"];
    LogUtil.v("name:$name");

    var phone = logBean["phone"];
    LogUtil.v("phone:$phone");

    expires_in = logBean["expires_in"];
    setState(() {
      name = name;
    });

    var access_token = logBean["access_token"];


    id = await Storage.getId();  //注意必须要用 await来修饰
    LogUtil.v("获取登录的id:$id");
    setState(() {
       id = id;
    });

//    LogUtil.v("access_token:$access_token");
  }

  /**
   * 版本号
   */
  getVersionNumber() async {
//    PackageInfo packageInfo = await PackageInfo.fromPlatform();
//    String version = packageInfo.version;//版本号
//    String buildNumber = packageInfo.buildNumber;//版本构建号

    PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
      String appName = packageInfo.appName;
      String packageName = packageInfo.packageName;
      String version = packageInfo.version;
      String buildNumber = packageInfo.buildNumber;

      LogUtil.v("版本号version:$version"); // 1.0.1
      LogUtil.v("版本号buildNumber:$buildNumber"); // 1

      setState(() {
        this.version = version;
      });
    });

//    LogUtil.v("版本号version:$version");
//    LogUtil.v("版本号buildNumber:$buildNumber");
  }


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    TLSizeFit.initialize();
    ScreenAdapter.init(context);
    LogUtil.v("个人中心。。。build");
    return FilmContent();
  }

  Widget FilmContent() {
//    return Container(
//      color: YColors.t, // 设置背景色
    return SingleChildScrollView(
        child: Container(
            color: YColors.t,
//            color: Color(0xffF2F1F6),
            // 设置背景色
            width: double.infinity,
//            margin: EdgeInsets.only(top: TLSizeFit.setPx(60)),

            child: Column(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.fromLTRB(TLSizeFit.setPx(40),
                      TLSizeFit.setPx(100), 0, TLSizeFit.setPx(20)),
                  color: YColors.l,
                  width: double.infinity,
                  child: Row(
                    children: <Widget>[
                      ClipOval(
                        // 圆形头像
                        // 设置头像
                        child: Image.asset(
                          'images/head.png',
                          width: TLSizeFit.setPx(70),
                          height: TLSizeFit.setPx(70),
                          // 设置图片的缩放模式
                          fit: BoxFit.cover,
                        ),
                      ),
//                    Container(
//                      margin: EdgeInsets.only(right: 10.0),
//                      width: 60.0,
//                      height: 60.0,
//                      decoration: BoxDecoration(
//                          shape: BoxShape.rectangle, //可以设置角度，BoxShape.circle直接圆形
//                          borderRadius: BorderRadius.circular(100.0),
//                          image: DecorationImage(
//                            fit: BoxFit.fill,
//                            image: AssetImage(
//                              "images/a.jpeg",
//                            ),
//                          )
//                      ),
//                    ),
                      SizedBox(
                        width: TLSizeFit.setPx(20),
                      ),
                      Expanded(
                          flex: 1,
                          child: Container(
                            height: TLSizeFit.setPx(72),
//                          color: YColors.h,
                            margin: EdgeInsets.fromLTRB(
                                0, TLSizeFit.setPx(0), 0, 0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: <Widget>[
                                SizedBox(
                                  height: TLSizeFit.setPx(6),
                                ),
                                Text(
                                  "欢迎您,${name != null ? name : ''}",
                                  style: TextStyle(
                                      color: YColors.t,
                                      fontSize: ScreenAdapter.size(39)),
                                ),
                                SizedBox(
                                  height: TLSizeFit.setPx(6),
                                ),
                                Text(
                                  "工号：${expires_in != null ? expires_in : ''}",
                                  style: TextStyle(
                                      color: YColors.t,
                                      fontSize: ScreenAdapter.size(28)),
                                ),
                                SizedBox(
                                  height: TLSizeFit.setPx(4),
                                ),
//                                Text(
//                                  '高级认证',
//                                  style: TextStyle(
//                                    color: YColors.d,
//                                    fontSize: ScreenAdapter.size(24),
//                                    backgroundColor: Color(0xffF2F2F6),
//                                  ),
//                                )
                              ],
                            ),
                          )),
//                      Image.asset(
//                        'images/user_home_arrow.png',
//                        width: TLSizeFit.setPx(18),
//                        height: TLSizeFit.setPx(18),
//                      ),
                    ],
                  ),
                ),
                SizedBox(
                  height: TLSizeFit.setPx(26),
                ),
//                Divider(
//                  height: 2,
//                  endIndent: 15,
//                  indent: 15,
//                ),

                InkWell(
                  child: Container(
                    margin: EdgeInsets.fromLTRB(
                        TLSizeFit.setPx(20), 0, TLSizeFit.setPx(20), 0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text("修改密码", style:TextStyle(fontSize: ScreenAdapter.size(30)),),
                        Image.asset(
                          'images/user_home_arrow.png',
                          width: TLSizeFit.setPx(18),
                          height: TLSizeFit.setPx(18),
                        ),
                      ],
                    ),
                  ),
                  onTap: (){
                    Navigator.pushNamed(context, "/ChangeCodePage",arguments: {Global.FLAG: ""});
                  },
                ),
                SizedBox(
                  height: TLSizeFit.setPx(18),
                ),
                Divider(
                  height: 2,
                  endIndent: 15,
                  indent: 15,
                ),
                InkWell(
                  child: Container(
                    margin: EdgeInsets.fromLTRB(
                        TLSizeFit.setPx(20), 0, TLSizeFit.setPx(20), 0),
                    height: TLSizeFit.setPx(54),
                    child: Row(
                      children: <Widget>[
//                      Image.asset(
//                        "images/personcenter1.png",
//                        width: TLSizeFit.setPx(26),
//                        height: TLSizeFit.setPx(26),
//                      ),
                        Expanded(
                            flex: 1,
                            child: Text(
                              "退出登录",
                              style:
                                  TextStyle(fontSize: ScreenAdapter.size(30)),
                            )),
                        Image.asset(
                          'images/user_home_arrow.png',
                          width: TLSizeFit.setPx(18),
                          height: TLSizeFit.setPx(18),
                        ),
                      ],
                    ),
                  ),
                  onTap: () {

                    _loginOutDialog();
                  },
                ),
//                Text("用户id:${id != null ? id : ''}", style:TextStyle(fontSize: ScreenAdapter.size(30))),

                Container(
                    margin: EdgeInsets.fromLTRB(
                        TLSizeFit.setPx(20), 0, TLSizeFit.setPx(20), 0),
                    height: TLSizeFit.setPx(54),

                    child: Row(
                      children: <Widget>[
                        Expanded(
                            flex: 1,
                            child: Text(
                              "版本号",
                              style: TextStyle(fontSize: ScreenAdapter.size(30)),
                            )),
                        Text(version,
                            style: TextStyle(fontSize: ScreenAdapter.size(30))),
                      ],
                    )),



//                TextButton(onPressed: (){
//                  Navigator.pushNamed(context, "/HeadTest");
//                }, child: Text("跳转到头布局吧")),

//                Container(
//                  height: TLSizeFit.setPx(6),
//                  color: Color(0xffF0F0F0),
//                ),
              ],
            )));
//    );
  }

  _loginOutDialog() {
    showDialog(
        barrierDismissible: false, // 表示点击灰色背景的时候是否消失弹出框
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text("您确定要退出吗？"),
            actions: <Widget>[
              FlatButton(
                  onPressed: () {
//                    logoutHttp();
                    httpJPushRegistrationID();
                  },
                  child: Text("确认")),
              FlatButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: Text("取消"))
            ],
          );
        });
  }

  /**
   * 给后台提交极光的注册id
   */
  httpJPushRegistrationID() async {

    String registId  = await Storage.getString(Global.JPUSHREGISTERID);

    String url = GlobalUrl.JPUSHUPDATEBINDSTATUS;
    var map = {
      "registrationId": registId,
      "validFlag": "0", //1 登录 0 退出
    };
    String access_token = await Storage.getToken();
    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
    var mapHeaders = {
      Global.AUTHORIZATION: access_token,
      Global.CONTENT_TYPE: Global.APPLICATION_JSON
    };

    HttpUtil.post(url,
        context: this.context,
        data: map,
        headers: mapHeaders,
        success: (data) {
          LogUtil.v("极光的注册success:$data");
//          极光的注册success:{code: 200, success: true, data: null, msg: 操作成功}
          var jsonMap = BossBean.fromJson(data);
          String result = jsonMap.code;
          String message = jsonMap.msg;
          bool success = jsonMap.success;
          if(success){
            Storage.setString(Global.JPUSHREGISTERSTATE, "");
            logoutHttp();
          }else{
            ToastUtils.toast(message);
          }
        },
        error: (error) {
          LogUtil.v("极光的注册error:$error");
        });
  }


  /**
   * 退出登录
   */
  logoutHttp() async {
    String url = GlobalUrl.LOGOUTURL;
    var map = {"": ""};
    String access_token = await Storage.getToken();
    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
    var mapHeaders = {
      Global.AUTHORIZATION: access_token,
      Global.CONTENT_TYPE: Global.APPLICATION_JSON
    };

    HttpUtil.delete(url, data: map, headers: mapHeaders, success: (data) {
      print("退出了登录了");
//          接口的数据：{code: 200, success: true, data: null, msg: 注销成功}
      var success = data["success"];
//      LogUtil.v("success:$success");
      var message = data["msg"];
      var body = data["data"];
      var code = data["code"];
      if (success == true) {

//        JPush jpush = new JPush();
//        jpush.deleteAlias();  // 删除别名
        Storage.clear(); // 清除数据
        //跳转并关闭当前页面
        Navigator.pushAndRemoveUntil(
          context,
          new MaterialPageRoute(builder: (context) => new LoginPage()),
          (route) => route == null,
        );
      }
      ToastUtils.toast(message);
    }, error: (errorMsg) {});
  }
}
